<?php

namespace App\Http\Controllers\Student;

use App\Criteria\Student\Student\StudentBaseQueryCriteria;
use App\Http\Controllers\Controller;
use App\Http\Controllers\CurlRecordMethod;
use App\Http\Requests\Student\StudentBaseRequest;
use App\Libs\Tools\SystemCodeConstant;
use App\Models\Student\Mo\StudentExcelImportMO;
use App\Repositories\Student\StudentRepository;
use App\Validators\Student\StudentValidator;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Input;
use Maatwebsite\Excel\Facades\Excel;
use Prettus\Validator\Contracts\ValidatorInterface;
use Prettus\Validator\Exceptions\ValidatorException;


class StudentsController extends Controller
{
    use CurlRecordMethod;

    protected $index_page='student.student.studentMain';
    protected $add_page='student.student.studentAdd';
    protected $edit_page='student.student.studentEdit';

    protected $repository;
    protected $validator;
    protected $request;

    public function __construct(StudentRepository $repository, StudentValidator $validator,StudentBaseRequest $studentBaseRequest)
    {
        $this->repository = $repository;
        $this->validator  = $validator;
        $this->request =$studentBaseRequest;
    }

    public function getBaseQueryCriteria(){
        return new StudentBaseQueryCriteria;
    }

    protected function post_edit_data(){
        $id=$this->request->get('id');
        $all=$this->wrap_user_info($this->request->all());
        try {
            $this->validator->with($all)->passesOrFail(ValidatorInterface::RULE_UPDATE);
            if(!isset($all['is_macao_or_taiwan'])){$all['is_macao_or_taiwan']=SystemCodeConstant::NO;}
            if(!isset($all['is_only_child'])){$all['is_only_child']=SystemCodeConstant::NO;}
            if(!isset($all['is_lodge'])){$all['is_lodge']=SystemCodeConstant::NO;}
            if(!isset($all['is_learn_preschool'])){$all['is_learn_preschool']=SystemCodeConstant::NO;}
            if(!isset($all['is_leftover_child'])){$all['is_leftover_child']=SystemCodeConstant::NO;}
            $this->repository->update($all, $id);
            return $this->return_json_success();
        } catch (ValidatorException $e) {
            return $this->return_json_error($e);
        }
    }

    public function delete_data(){
        try {
            $ids=Input::get('ids');
            foreach ($ids as $id){
                $this->validator->with(['id'=>$id])->passesOrFail('DELETE');
            }
            DB::transaction(function () {
                $ids=Input::get('ids');
                $models=$this->repository->skipPresenter()->findWhereIn('id',$ids);
                foreach ($models as $model){
                    $model->delete();
                }
            });
            return $this->return_json_success();
        } catch (ValidatorException $e) {
            return $this->return_json_error($e);
        }
    }

    public function delete_clbum(){
        DB::transaction(function () {
            $ids=Input::get('ids');
            DB::table('student')->whereIn('id',$ids)->update([
                'clbum_id'=>0,
                'updated_user'=>Auth::user()['name'],
                'updated_at'=>date('Y-m-d H:i:s')
            ]);
            DB::table('clbum_ext')->whereIn('value',$ids)
                                  ->whereIn('system_code_type',[SystemCodeConstant::CLBUM_EXT_STUDENT_LEADER_TYPE,SystemCodeConstant::CLBUM_EXT_COURSE_LEADER_TYPE])
                                  ->update([
                                      'value'=>'',
                                      'updated_user'=>Auth::user()['name'],
                                      'updated_at'=>date('Y-m-d H:i:s')
                                  ]);
        });
        return $this->return_json_success();
    }

    public function import(){
        $reader=Excel::load(Input::file('file'));
        $reader = $reader->ignoreEmpty()->getSheet(0);
        $res = $reader->toArray();
        $studentExcelImport=new StudentExcelImportMO();
        if(count($res)<1){
            return $this->return_json_error_message('空excel');
        }
        $errorMsg=$studentExcelImport->convert($res)->verify();
        if($errorMsg!=null){
            return $this->return_json_error_message($errorMsg);
        }
        $errorMsg=$studentExcelImport->convert_results_data();
        if($errorMsg!=null){
            return $this->return_json_error_message($errorMsg);
        }
        DB::transaction(function () use(&$studentExcelImport) {
            $results=$studentExcelImport->getResults();
            foreach ($results as $key=>$result){
                $result=$this->wrap_user_info($result,true);
                $this->repository->skipPresenter()->create($result);
            }
        });
        return $this->return_json_success();
    }
}
